<template>
  <div class="project-container">
    <!-- 页面头部：标题+操作 -->
    <div class="page-header">
      <el-row :gutter="20" align="middle">
        <el-col>
          <h2>项目管理</h2>
        </el-col>
        <el-col :align="`right`">
          <el-button type="primary" size="small" @click="openAddDialog">
            <el-icon><Plus /></el-icon> 新建项目
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 项目列表 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 项目卡片（循环渲染） -->
      <el-col :span="6" v-for="(project, index) in projectList" :key="index">
        <el-card 
          class="project-card" 
          shadow="hover"
          @click="goToProjectDetail(project.id)"
        >
          <div class="project-header">
            <el-icon class="project-icon"><Folder /></el-icon>
            <div class="project-actions">
              <el-button 
                type="text" 
                size="mini" 
                icon="Edit" 
                @click.stop="openEditDialog(project)"
              />
              <el-button 
                type="text" 
                size="mini" 
                icon="Delete" 
                text-color="#f56c6c"
                @click.stop="deleteProject(project.id)"
              />
            </div>
          </div>
          <div class="project-name">{{ project.name }}</div>
          <div class="project-desc">{{ project.description || '无描述' }}</div>
          <div class="project-meta">
            <span>创建人：{{ project.creator }}</span>
            <span>更新时间：{{ formatTime(project.update_time) }}</span>
          </div>
          <div class="project-stats">
            <div class="stat-item">
              <div class="stat-label">用例数</div>
              <div class="stat-value">{{ project.case_count || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">报告数</div>
              <div class="stat-value">{{ project.report_count || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">通过率</div>
              <div class="stat-value">{{ project.pass_rate || 0 }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 空状态 -->
      <el-col :span="24" v-if="projectList.length === 0 && !loading">
        <div class="empty-state">
          <el-empty 
            description="暂无项目，点击新建项目开始测试"
            @click="openAddDialog"
          >
            <template #footer>
              <el-button type="primary" @click="openAddDialog">
                <el-icon><Plus /></el-icon> 新建项目
              </el-button>
            </template>
          </el-empty>
        </div>
      </el-col>
    </el-row>

    <!-- 新建/编辑项目弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑项目' : '新建项目'"
      width="500px"
    >
      <el-form
        ref="projectFormRef"
        :model="projectForm"
        :rules="projectRules"
        label-width="100px"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="projectForm.name" placeholder="请输入项目名称（如：电商API测试）" />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input
            v-model="projectForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入项目描述（可选）"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="owner">
          <el-input v-model="projectForm.owner" placeholder="请输入负责人姓名或账号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElEmpty, ElIcon } from 'element-plus'
import { Plus, Folder, Edit, Delete } from '@element-plus/icons-vue'
import request from '@/api/request'

// 项目列表数据
const projectList = ref([])
const loading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const projectFormRef = ref(null)
const projectForm = reactive({
  id: '',
  name: '',
  description: '',
  owner: ''
})

// 表单验证规则
const projectRules = reactive({
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  owner: [{ required: true, message: '请输入负责人', trigger: 'blur' }]
})

const router = useRouter()

// 页面挂载时加载项目列表
onMounted(() => {
  getProjectList()
})

// 1. 获取项目列表（对接Django接口）
const getProjectList = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/projects/')
    projectList.value = res.data || []
  } catch (error) {
    ElMessage.error('获取项目列表失败：' + (error.response?.data?.msg || error.message))
  } finally {
    loading.value = false
  }
}

// 2. 打开新建弹窗
const openAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 3. 打开编辑弹窗
const openEditDialog = (project) => {
  isEdit.value = true
  Object.assign(projectForm, JSON.parse(JSON.stringify(project)))
  dialogVisible.value = true
}

// 4. 提交表单（新增/编辑）
const submitForm = async () => {
  const valid = await projectFormRef.value.validate()
  if (!valid) return

  try {
    if (isEdit.value) {
      // 编辑项目
      await request.put(`/api/projects/${projectForm.id}/`, projectForm)
      ElMessage.success('项目编辑成功')
    } else {
      // 新增项目
      await request.post('/api/projects/', projectForm)
      ElMessage.success('项目创建成功')
    }
    dialogVisible.value = false
    getProjectList() // 刷新列表
  } catch (error) {
    ElMessage.error('操作失败：' + (error.response?.data?.msg || error.message))
  }
}

// 5. 删除项目
const deleteProject = (id) => {
  ElMessageBox.confirm(
    '确认删除该项目吗？项目下的用例、报告等数据也会被删除',
    '警告',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(async () => {
    try {
      await request.delete(`/api/projects/${id}/`)
      ElMessage.success('项目删除成功')
      getProjectList()
    } catch (error) {
      ElMessage.error('删除失败：' + (error.response?.data?.msg || error.message))
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 6. 进入项目详情页
const goToProjectDetail = (projectId) => {
  router.push(`/project-detail/${projectId}`) // 跳转到项目详情页（需单独开发）
}

// 辅助函数：重置表单
const resetForm = () => {
  projectForm.id = ''
  projectForm.name = ''
  projectForm.description = ''
  projectForm.owner = ''
  if (projectFormRef.value) {
    projectFormRef.value.resetFields()
  }
}

// 辅助函数：格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '未知'
  try {
    const date = new Date(timeStr)
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return timeStr
  }
}
</script>

<style scoped lang="scss">
.project-container {
  padding: 20px;
}

.page-header {
  padding: 10px 0;
  h2 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }
}

// 项目卡片样式
.project-card {
  height: 100%;
  cursor: pointer;
  transition: all 0.3s;
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }
  .project-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    .project-icon {
      font-size: 24px;
      color: #4361ee;
    }
    .project-actions {
      opacity: 0; // 鼠标悬停时显示操作按钮
      transition: opacity 0.3s;
    }
  }
  &:hover .project-actions {
    opacity: 1;
  }
  .project-name {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .project-desc {
    font-size: 13px;
    color: #666;
    margin-bottom: 15px;
    height: 40px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    --webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .project-meta {
    font-size: 12px;
    color: #909399;
    margin-bottom: 15px;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  .project-stats {
    display: flex;
    justify-content: space-between;
    padding-top: 10px;
    border-top: 1px dashed #eee;
    .stat-item {
      text-align: center;
      flex: 1;
      .stat-label {
        font-size: 12px;
        color: #909399;
      }
      .stat-value {
        font-size: 14px;
        font-weight: 500;
        color: #333;
      }
    }
  }
}

// 空状态样式
.empty-state {
  padding: 50px 0;
  text-align: center;
}

// 弹窗底部样式
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>